package com.loopj.ohos.http.sample;


import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.AsyncHttpResponseHandler;
import com.loopj.ohos.http.RequestHandle;
import com.loopj.ohos.http.ResponseHandlerInterface;
import com.loopj.ohos.http.ext.LocalHiLog;
import com.loopj.ohos.http.sample.ext.Toast;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import ohos.aafwk.ability.Ability;
import ohos.eventhandler.EventRunner;

import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.*;

/**
 * AsyncBackgroundThreadSample
 */
public class AsyncBackgroundThreadSample extends SampleParentAbility {
    private static final String LOG_TAG = "AsyncBackgroundThreadSample";

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers, HttpEntity entity, final ResponseHandlerInterface responseHandler) {

        final Ability ctx = this;
        FutureTask<RequestHandle> future = new FutureTask<>(new Callable<RequestHandle>() {
            /**
             * string
             *
             * @return string
             */
            public RequestHandle call() {
                LocalHiLog.info(LOG_TAG, "Executing GET request on background thread");
                return client.get(ctx, URL, headers, null, responseHandler);
            }
        });

        executor.execute(future);

        RequestHandle handle = null;
        try {
            handle = future.get(5, TimeUnit.SECONDS);
            LocalHiLog.info(LOG_TAG, "Background thread for GET request has finished");
        } catch (Exception e) {
            Toast.show(ctx, e.getMessage());
        }

        return handle;
    }

    @Override
    public int getSampleTitle() {
        return ResourceTable.String_title_async_background_thread;
    }

    @Override
    public boolean isRequestBodyAllowed() {
        return false;
    }

    @Override
    public boolean isRequestHeadersAllowed() {
        return false;
    }

    @Override
    public String getDefaultURL() {
        return PROTOCOL + "httpbin.org/get";
    }

    @Override
    public ResponseHandlerInterface getResponseHandler() {

        FutureTask<ResponseHandlerInterface> future = new FutureTask<>(new Callable<ResponseHandlerInterface>() {

            @Override
            public ResponseHandlerInterface call() throws Exception {
                LocalHiLog.info(LOG_TAG, "Creating AsyncHttpResponseHandler on background thread");
                return new AsyncHttpResponseHandler(EventRunner.getMainEventRunner()) {

                    @Override
                    public void onStart() {
                        clearOutputs();
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                        LocalHiLog.info(LOG_TAG, String.format(Locale.US, "onSuccess executing on main thread : %B", EventRunner.current() == EventRunner.getMainEventRunner()));
                        debugHeaders(LOG_TAG, headers);
                        debugStatusCode(LOG_TAG, statusCode);
                        debugResponse(LOG_TAG, new String(response, Charset.defaultCharset()));
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable ee) {
                        LocalHiLog.info(LOG_TAG, String.format(Locale.US, "onFailure executing on main thread : %B", EventRunner.current() == EventRunner.getMainEventRunner()));
                        debugHeaders(LOG_TAG, headers);
                        debugStatusCode(LOG_TAG, statusCode);
                        debugThrowable(LOG_TAG, ee);
                        if (errorResponse != null) {
                            debugResponse(LOG_TAG, new String(errorResponse,Charset.defaultCharset()));
                        }
                    }

                    @Override
                    public void onRetry(int retryNo) {
                        Toast.show(AsyncBackgroundThreadSample.this, String.format(Locale.US, "Request is retried, retry no. %d", retryNo));
                    }
                };
            }
        });

        executor.execute(future);

        ResponseHandlerInterface responseHandler = null;
        try {
            responseHandler = future.get();
            LocalHiLog.info(LOG_TAG, "Background thread for AsyncHttpResponseHandler has finished");
        } catch (Exception e) {
            LocalHiLog.info(LOG_TAG, e.getMessage());
        }

        return responseHandler;
    }
}
